package com.bw.module_service.viewmodel

import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.lib_common.appContext
import com.bw.lib_common.base.BaseViewModel
import com.bw.lib_common.base.state.Failed
import com.bw.lib_common.base.state.RequestEvent
import com.bw.lib_common.base.state.Success
import com.bw.lib_common.observeWithLifecycle
import com.bw.lib_log.utils.LoggerUtil
import com.bw.module_service.R
import com.bw.module_service.model.AddVipModel
import com.bw.module_service.model.AnnouncementModelItem
import com.bw.module_service.model.CarModel
import com.bw.module_service.model.GetSignInfoModel
import com.bw.module_service.model.InspectionModel
import com.bw.module_service.model.InspectionModelItem
import com.bw.module_service.model.ParkSpaceModel
import com.bw.module_service.model.ParkSpaceModelItem
import com.bw.module_service.model.ProvinceModel
import com.bw.module_service.model.ServiceModel
import com.bw.module_service.model.SignModel
import com.bw.module_service.model.TaskEntity
import com.bw.module_service.repository.ServiceRepository
import com.bw.module_service.ui.AnnouncementForm
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import okhttp3.RequestBody
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject

@HiltViewModel
open class ServiceViewModel @Inject constructor(private val repository: ServiceRepository):BaseViewModel(){

    val serviceList = mutableListOf<ServiceModel>()

    fun initList(){
        serviceList.add(ServiceModel(R.mipmap.cheliangguanli,"车辆管理"))
        serviceList.add(ServiceModel(R.mipmap.cheweiguanli_service,"车位管理"))
        serviceList.add(ServiceModel(R.mipmap.visitor,"访客管理"))
        serviceList.add(ServiceModel(R.mipmap.repair_service,"维修管理"))
        serviceList.add(ServiceModel(R.mipmap.notice_service,"公告管理"))
        serviceList.add(ServiceModel(R.mipmap.kaoqinguanli,"考勤管理"))
        serviceList.add(ServiceModel(R.mipmap.jishitongxun,"即时通讯"))
        serviceList.add(ServiceModel(R.mipmap.shebeiguanli,"设备管理"))
        serviceList.add(ServiceModel(R.mipmap.house_service,"房源信息"))
        serviceList.add(ServiceModel(R.mipmap.house_service2,"物业报修"))
        serviceList.add(ServiceModel(R.mipmap.xunjianguanli,"巡检管理"))
        serviceList.add(ServiceModel(R.mipmap.vip_service,"月卡会员"))
    }

    //车位
    private val parkspaceLiveData by lazy {
        MutableLiveData<ParkSpaceModel>()
    }
    val _parkspaceLiveData:LiveData<ParkSpaceModel> = parkspaceLiveData
    fun getParkSpace(spaceType: String) {
        execute(
            action = repository.getParkSpace(spaceType),
            onFinish = {
                parkspaceLiveData.value = it.data
                LoggerUtil.d("zty",it.message)
            }
        )
    }

    //添加车位
    private val addParkSpaceLiveData by lazy {
        MutableLiveData<ParkSpaceModelItem>()
    }

    val _addParkSpaceLiveData: LiveData<ParkSpaceModelItem> = addParkSpaceLiveData

    fun addParkSpace(body: RequestBody) {
        execute(
            action = repository.addParkSpace(body),
            onFinish = {
                addParkSpaceLiveData.value = it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }

    //删除车位
    private val deleteCarSpaceLiveData by lazy {
        MutableLiveData<Boolean>()
    }
    val _deleteCarSpaceLiveData: LiveData<Boolean> = deleteCarSpaceLiveData
    fun deleteCarSpace(id:Int){
        execute(
            action = repository.deleteParkSpace(id),
            onFinish = {
                deleteCarSpaceLiveData.value = it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }
    //车辆
    private val carLiveData by lazy {
        MutableLiveData<CarModel>()
    }
    val _carLiveData:LiveData<CarModel> = carLiveData
    fun getCar(id:Int) {
        execute(
            action = repository.getCar(id),
            onFinish = {
                carLiveData.value = it.data
                LoggerUtil.d("zty",it.message)
            }
        )
    }

    //根据车牌获取车辆
    private val byNumCarLiveData by lazy {
        MutableLiveData<CarModel>()
    }
    val _byNumCarLiveData: LiveData<CarModel> = byNumCarLiveData
    fun byNumGetCar(licensePlate: String) {
        execute(
            action = repository.byNumGetCar(licensePlate),
            onFinish = {
                byNumCarLiveData.value = it.data
                LoggerUtil.d("zty", it.message)
            }
        )
    }

    //添加车辆
    private val addCarLiveData by lazy {
        MutableLiveData<CarModel>()
    }
    val _addCarLiveData: LiveData<CarModel> = addCarLiveData
    fun addCar(body: RequestBody) {
        execute(
            action = repository.addCar(body),
            onFinish = {
                addCarLiveData.value = it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }

    //删除车辆
    private val deleteCarLiveData by lazy {
        MutableLiveData<Boolean>()
    }
    val _deleteCarLiveData: LiveData<Boolean> = deleteCarLiveData
    fun deleteCar(id:Int) {
        execute(
            action = repository.deleteCar(id),
            onFinish = {
                deleteCarLiveData.value = it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }

    //获取省份简码
    private val provincesLiveData by lazy {
        MutableLiveData<ProvinceModel>()
    }
    val _provincesLiveData: LiveData<ProvinceModel> = provincesLiveData
    fun getProvinces() {
        execute(
            action = repository.getProvinces(),
            onFinish = {
                provincesLiveData.value = it.data
            }
        )
    }

    //修改车辆信息
    private val updateCarLiveData by lazy {
        MutableLiveData<CarModel>()
    }
    val _updateCarLiveData: LiveData<CarModel> = updateCarLiveData
    fun updateCar(id:Int,body: RequestBody) {
        execute(
            action = repository.updateCar(id,body),
            onFinish = {
                updateCarLiveData.value = it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }


    private val inspectionLiveData by lazy {
        MutableLiveData<InspectionModel>()
    }
    val inspectionLiveData_:LiveData<InspectionModel> = inspectionLiveData

    fun getPatrolPoints() {
        execute(
            action = repository.getPatrolPoints(),
            onFinish = {
                inspectionLiveData.value=it.data
            }
        )
    }


    private val  signInfoLiveData by lazy {
        MutableLiveData<GetSignInfoModel>()
    }
    val signInfoLiveData_:LiveData<GetSignInfoModel> = signInfoLiveData
    var aa:GetSignInfoModel = GetSignInfoModel()
    fun getSignInfo(userId:Int){
        execute(
            action = repository.getSignInfo(userId),
            onFinish = {
               signInfoLiveData.value = it.data
                aa = it.data
            },


        )
    }

    private val getSign by lazy {
        MutableLiveData<SignModel>()
    }

    val getSign_:LiveData<SignModel> = getSign
    fun getSign(map:Map<String,Any>){
        execute(
            action = repository.getSign(map),
            onFinish = {
                getSign.value = it.data
            }
        )
    }

    private val addPollingLiveData by lazy {
        MutableLiveData<InspectionModelItem>()
    }
    val addPollingLiveData_: LiveData<InspectionModelItem> = addPollingLiveData
    fun addPolling(body: RequestBody) {
        execute(
            action = repository.addPolling(body),
            onFinish = {
                addPollingLiveData.value = it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }

    private val PollingDetailLiveData by lazy {
        MutableLiveData<InspectionModelItem>()
    }
    val PollingDetailLiveData_:LiveData<InspectionModelItem> = PollingDetailLiveData
    fun getPollingDetailById(id: Int) {
        execute(
            action = repository.getPollingDetailById(id),
            onFinish = {
                PollingDetailLiveData.value = it.data
            }
        )
    }

    private val addVipLiveData by lazy {
        MutableLiveData<AddVipModel>()
    }
    val addVipLiveData_:LiveData<AddVipModel> = addVipLiveData

     fun addVip(body: RequestBody) {
         viewModelScope.launch {
             repository.addVip(body).collect{
                 addVipLiveData.value = it
             }
         }

    }
    private val vipLiveData by lazy {
        MutableLiveData<AddVipModel>()
    }
    val vipLiveData_:LiveData<AddVipModel> = vipLiveData
    fun getVipByUserId(userId:Int){
        viewModelScope.launch {
            repository.getVipInfo(userId).collect{
                vipLiveData.value = it
            }
        }
    }

    /**
     * 计算到期日期
     */
    @RequiresApi(Build.VERSION_CODES.O)
    fun calculateDueDate(startDateStr: String, daysToAdd: Int): String {
        // 解析办理日期（格式示例："2023-10-01"）
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        val startDate = LocalDate.parse(startDateStr, formatter)

        // 计算到期日期
        val dueDate = startDate.plusDays(daysToAdd.toLong())

        // 返回格式化后的日期
        return dueDate.format(formatter)
    }


   /**
    * 判断是否已到期
    * @param dueDateStr 到期日期（格式："yyyy-MM-dd"）
    * @return true = 已到期，false = 未到期
    */
    fun isExpiredLegacy(dueDateStr: String): Boolean {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val dueDate = dateFormat.parse(dueDateStr)!!
        val currentDate = Calendar.getInstance().time // 获取当前日期
        return currentDate.after(dueDate) // 当前日期 > 到期日期 → 已到期

    }


    /**
     * 获取巡检列表
     */
    private val taskListLiveData by lazy {
        MutableLiveData<List<TaskEntity>>()
    }
    val taskListLiveData_:LiveData<List<TaskEntity>> = taskListLiveData
    fun getTaskList() {
        execute(
            action = repository.getTaskList(),
            onFinish = {
                taskListLiveData.value=it.data
            },
            onError = {
                Toast.makeText(appContext, it, Toast.LENGTH_SHORT).show()
            }
        )
    }

    private val announcementLiveData by lazy {
        MutableLiveData<List<AnnouncementModelItem>>()
    }

    val announcementLiveData_:LiveData<List<AnnouncementModelItem>> = announcementLiveData

    //公告
    fun getAnnouncement() {
        execute(
            action = repository.getAnnouncement(),
            onFinish = {
                announcementLiveData.value = it.data
            }
        )
    }

    private val postAnnouncementLiveData by lazy {
        MutableLiveData<AnnouncementModelItem>()
    }

    val postAnnouncementLiveData_:LiveData<AnnouncementModelItem> = postAnnouncementLiveData

    //发布公告
    fun postAnnouncement(map: AnnouncementForm){
        execute(
            action = repository.postAnnouncement(map),
            onFinish = {
                postAnnouncementLiveData.value = it.data
            }
        )
    }

}